package cn.lili.modules.promotion.serviceimpl;

import cn.lili.modules.promotion.entity.dos.GreenPool;
import cn.lili.modules.promotion.mapper.GreenPoolMapper;
import cn.lili.modules.promotion.service.GreenPoolService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;

/**
 * @author xiangqian
 * @version 1.0
 * @data 2023/12/20 15:39
 */
@Service
@RequiredArgsConstructor
public class GreenPoolServiceImpl extends ServiceImpl<GreenPoolMapper, GreenPool> implements GreenPoolService {

    /**
     * 往绿色积分池中添加绿色积分
     *
     * @param pool 绿色积分
     */
    @Override
    public Boolean addGreenPool(BigDecimal pool) {
        boolean flag;

        GreenPool greenPool = getGreenPool();
        if (greenPool == null) {
            greenPool = new GreenPool();
            greenPool.setGreenPool(pool);
            flag = this.save(greenPool);
        } else {
            greenPool.setGreenPool(pool.add(greenPool.getGreenPool()));
            flag = this.updateById(greenPool);
        }
        return flag;
    }

    /**
     * 往绿色积分池中减少绿色积分
     *
     * @param pool 绿色积分
     */
    @Override
    public Boolean removeGreenPool(BigDecimal pool) {
        GreenPool greenPool = getGreenPool();
        Assert.notNull(greenPool, "绿色积分池数据为空");

        BigDecimal newPool = greenPool.getGreenPool().subtract(pool);
        Assert.isTrue(newPool.compareTo(new BigDecimal(0)) > 0, "绿色积分池绿色积分不足以抵扣");

        greenPool.setGreenPool(newPool);
        return this.updateById(greenPool);
    }

    /**
     * 查询绿色积分池数据
     */
    @ApiModelProperty("查询绿色积分池数据")
    public GreenPool getGreenPool() {
        LambdaQueryWrapper<GreenPool> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.last("limit 1");
        return this.getBaseMapper().selectOne(lambdaQueryWrapper);
    }
}
